<template>
  <div class="login-container d-flex align-items-center justify-content-center">
    <div class="card p-5 shadow-lg">
      <h3 class="card-title text-center mb-4">登录到 SuperDe</h3>
      <form @submit.prevent="handleLogin">
        <!-- 电子邮件输入框 -->
        <div class="mb-4 position-relative">
          <label for="email" class="form-label">电子邮件</label>
          <input
            type="email"
            class="form-control form-control-lg rounded-pill"
            id="email"
            v-model="email"
            required
            placeholder="请输入您的电子邮件"
          />
        </div>

        <!-- 密码输入框 -->
        <div class="mb-4 position-relative">
          <label for="password" class="form-label">密码</label>
          <input
            :type="showPassword ? 'text' : 'password'"
            class="form-control form-control-lg rounded-pill"
            id="password"
            v-model="password"
            required
            placeholder="请输入您的密码"
          />
          <!-- 密码可视化切换按钮 -->
          <span class="password-toggle" @click="togglePasswordVisibility">
            <i :class="showPassword ? 'bi bi-eye-slash' : 'bi bi-eye'"></i>
          </span>
        </div>

        <!-- 登录按钮 -->
        <button
          type="submit"
          class="btn btn-primary btn-lg w-100 rounded-pill"
          :disabled="isLoading"
        >
          <span v-if="isLoading">登录中...</span>
          <span v-else>登录</span>
        </button>
      </form>

      <p class="mt-4 text-center">
        还没有账号？
        <router-link to="/register">注册</router-link>
      </p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'LoginView',
  data() {
    return {
      email: '',
      password: '',
      showPassword: false, // 控制密码可视化
      isLoading: false,    // 控制加载状态
    };
  },
  created() {
    // 如果本地已经记录为登录状态，那么直接跳转到主页（您可以改成跳其他地方）
    const isAuthenticated = localStorage.getItem('isAuthenticated');
    if (isAuthenticated === 'true') {
      // 比如跳转到背诵页面
      this.$router.push({ name: 'recite' });

    }
  },
  methods: {
    async handleLogin() {
      try {
        this.isLoading = true;
        // 发起登录请求
        const response = await axios.post('http://localhost:8080/api/login/', {
          email: this.email,
          password: this.password,
        });
        // 假设后端返回的结构类似：
        // {
        //   "detail": "登录成功。",
        //   "user": {...},
        //   "tokens": {
        //     "refresh": "xxx",
        //     "access": "yyy"
        //   }
        // }
        const { tokens, user } = response.data;

        // 登录成功后，将 tokens、user 信息保存到 localStorage
        localStorage.setItem('accessToken', tokens.access);
        localStorage.setItem('refreshToken', tokens.refresh || '');
        localStorage.setItem('user', JSON.stringify(user));
        // 关键：标记已登录
        localStorage.setItem('isAuthenticated', 'true');
        window.location.reload();
        // 重定向到背诵页面（您可以改成 "read" 或 "listen" 或主页 "home"）
        this.$router.push({ name: 'recite' });
      } catch (error) {
        console.error(error);
        if (error.response) {
          alert(error.response.data.detail || '登录失败，请检查邮箱或密码。');
        } else {
          alert('网络错误或服务器无响应。');
        }
      } finally {
        this.isLoading = false;
      }
    },
    togglePasswordVisibility() {
      this.showPassword = !this.showPassword;
    },
  },
};
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f4f8, #d9e2ec);
}

.card {
  max-width: 400px;
  width: 100%;
  border: none;
  border-radius: 20px;
  background-color: #ffffff;
}

.card-title {
  color: #333333;
  font-weight: 600;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    'Helvetica Neue', Arial, sans-serif;
}

.form-label {
  color: #555555;
  font-weight: 500;
}

.form-control {
  padding-right: 2.5rem; /* 为密码可视化按钮留出空间 */
  font-size: 1rem;
}

.password-toggle {
  position: absolute;
  top: 70%;
  right: 1.5rem;
  transform: translateY(-50%);
  cursor: pointer;
  color: #aaa;
}

.password-toggle:hover {
  color: #4a90e2;
}

.btn-primary {
  background-color: #4a90e2;
  border: none;
  font-weight: 600;
  transition: background-color 0.3s ease;
}

.btn-primary:hover {
  background-color: #357ab8;
}

.shadow-lg {
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

/* 响应式调整 */
@media (max-width: 576px) {
  .card {
    padding: 2rem;
  }
}
</style>
